import { GoodResponse } from 'src/util/response';
import { OrderService } from 'src/service/order/order.service';
import { ToolsService } from 'src/service/tools/tools.service';
import { UserService } from 'src/service/user/user.service';
import { AddressService } from 'src/service/address/address.service';
import { ResponseInterceptor } from 'src/interceptor/response/response.interceptor';
import {
    Controller,
    Get,
    Post,
    Req,
    UseInterceptors,
    BadRequestException,
    Res,
    Query,
    Body,
    InternalServerErrorException,
} from '@nestjs/common';
import config from 'src/config/config';
import { CookieService } from 'src/service/cookie/cookie.service';
import Alipay from 'alipay-mobile';
import { AlipayOption, AlipayPublicArgs } from 'alipay-mobile/dist/config';
@UseInterceptors(ResponseInterceptor)
@Controller(`${config.shopApiPath}/buy`)
export class BuyController {
    private aliPayService;
    constructor(
        private readonly cookieService: CookieService,
        private readonly addressService: AddressService,
        private readonly userService: UserService,
        private readonly toolsService: ToolsService,
        private readonly orderService: OrderService,
    ) {}
    @Get('checkout')
    async getCheckoutList(@Req() req) {
        const list = (this.cookieService.get(req, config.cartKey) || []).filter((item) => item.checked);
        const price = list.reduce((pre, item) => pre + item.price * item.num, 0);
        return { list, price };
    }
    @Post('doOrder')
    async doOrder(@Req() req, @Res() res) {
        const { _id: uid } = await this.userService.getUser(req);
        const address = (await this.addressService.find({ uid })).find((item) => item.default_address);
        if (!address) throw new BadRequestException('请选择收货地址');
        const checkedCartList = (this.cookieService.get(req, config.cartKey) || []).filter((item) => item.checked);
        if (!checkedCartList.length) throw new BadRequestException('请选择商品');
        const unCheckedCartList = (this.cookieService.get(req, config.cartKey) || []).filter((item) => !item.checked);
        const all_price = checkedCartList.reduce((pre, item) => pre + item.num * item.price, 0);
        const order_no = this.toolsService.generateOrderId();
        const { name, phone, zipcode, address: addressDetail } = address;
        const order = await this.orderService.create({
            uid,
            all_price,
            order_no,
            name,
            phone,
            address: addressDetail,
            zipcode,
            pay_status: 0,
            pay_type: '',
            order_status: 0,
        });
        const { _id: order_id } = order;
        checkedCartList.forEach(async (item) => {
            const { title, _id: product_id, goods_img: product_img, price: product_price, num: product_num, color, goods_version } = item;
            await this.orderService.createOrderItem({
                order_id,
                product_title: `${title}-${color}-${goods_version}`,
                product_id,
                product_img,
                product_price,
                product_num,
            });
        });
        this.cookieService.set(res, config.cartKey, unCheckedCartList);
        req.session.orderSign = null;
        res.send(GoodResponse(order, '结算成功'));
    }
    @Get('orderInfo')
    async getOrderDetail(@Query() query) {
        const { _id } = query;
        const order = await this.orderService.find({ _id });
        const orderItems = await this.orderService.findOrderItem({ order_id: _id });
        if (!order.length || !orderItems.length) throw new BadRequestException('订单不存在');
        return {
            order: order[0],
            orderItems,
        };
    }
    createAlipayService() {
        if (!this.aliPayService) this.aliPayService = new Alipay(config.aliPay.options as unknown as AlipayOption);
    }
    @Post('pay')
    async pay(@Body() body: { type: number; order_no: string }) {
        const { type = 1, order_no } = body;
        if (!order_no) throw new BadRequestException('订单id不能为空');
        const order = await this.orderService.find({ order_no });
        if (!order.length) throw new BadRequestException('订单不存在');
        const { all_price: total_amount, _id: order_id } = order[0];
        const orderItems = await this.orderService.findOrderItem({ order_id });
        if (!orderItems) throw new BadRequestException('订单不存在');
        const subject = orderItems.map((item) => item.product_title).join('、');
        if (type === 1) {
            this.createAlipayService();
            const apiparams = {
                subject,
                out_trade_no: order_no,
                total_amount: total_amount.toString(),
            };
            const result = this.aliPayService.createPageOrderURL(apiparams, config.aliPay.basicParams as AlipayPublicArgs);
            const { code, data, message } = result;
            if (code === 0) {
                return data;
            } else {
                console.log({ message });
                throw new InternalServerErrorException('支付出错');
            }
        } else if (type === 2) {
        }
    }
    @Post('aliPayNotify')
    async aliPayNotify(@Body() body) {
        this.createAlipayService();
        const checkResult = this.aliPayService.makeNotifyResponse(body);
        const { code, message, data } = checkResult;
        if (code === 0) {
            const { out_trade_no: order_no } = data;
            await this.orderService.getModel().updateOne({ order_no }, { pay_status: 1, pay_type: 'alipay', order_status: 1 });
            return {};
        } else {
            throw new InternalServerErrorException(message || '签名错误');
        }
    }
}
